package routers

import (
	"crypto/sha1"
	b64 "encoding/base64"
	"net/http"
	"strconv"
	"strings"
	"time"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/popedom"

	"github.com/henrylee2cn/mahonia"

	log "github.com/sirupsen/logrus"

	jwt "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

// UserLoginClaims 用户登录凭证
type UserLoginClaims struct {
	UserID      int    `json:"ID"`
	OrganID     int    `json:"OrganID"`
	ParentOrgID int    `json:"ParentOrgID"`
	Sjy         string `json:"sjy"`
	iscsh       string `json:"iscsh"`
	jwt.StandardClaims
}

// Login 用户登录
func Login(c echo.Context) error {
	username := c.FormValue("username")
	password := c.FormValue("password")
	//查询
	rows, err := base.DB.Raw("SELECT EMID,DPID,PDID,PWD,STATUS FROM DIM_USER WHERE EMNO=?", username).Rows()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	defer rows.Close()
	var (
		id      int
		organID int
		pOrgID  int
		pwd     string
		iscsh   string
		status  string
	)
	if rows.Next() {
		rows.Scan(&id, &organID, &pOrgID, &pwd, &status)
	}
	if status == "2" || status == "3" {
		return echo.NewHTTPError(http.StatusBadRequest, "工号处于已离职/已停用状态，无权限登录。")
	}
	h := sha1.New()
	enc := mahonia.NewEncoder("UTF-16LE")
	userAndPwd := enc.ConvertString(username + password)
	h.Write([]byte(userAndPwd))
	pwdH := b64.StdEncoding.EncodeToString(h.Sum(nil))
	if pwdH != pwd {
		return echo.NewHTTPError(http.StatusBadRequest, "工号或密码不正确！")
	}
	if password == "00000000" {
		iscsh = "true"
	} else {
		iscsh = "false"
	}
	ip := string([]rune(getIpAttr(c.Request()))[:strings.Index(getIpAttr(c.Request()), ":")])
	base.DB.Exec("INSERT INTO t_UseLog(UserID,UseTime,UseContent,UseType,TableName,UserIP)VALUES(?,?,'用户登录','登录','t_SysUser',?)", id, time.Now(), ip)
	// Set custom claims
	Sjy := "ODS"
	if organID == 61 || organID == 83 || organID == 84 || organID == 85 {
		Sjy = "EDW"
	}
	claims := &UserLoginClaims{
		id,
		organID,
		pOrgID,
		Sjy,
		iscsh,
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Hour * 2).Unix(),
		},
	}
	// Create token with claims
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// Generate encoded token and send it as response.
	t, err := token.SignedString([]byte("secret"))
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	err = popedom.LoadUserPermsToRedis(nil, id)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, map[string]string{
		"token":  t,
		"userID": strconv.Itoa(id),
		"orgID":  strconv.Itoa(organID),
		"pOrgID": strconv.Itoa(pOrgID),
		"iscsh":  iscsh,
	})
}

func accessible(c echo.Context) error {
	return c.String(http.StatusOK, "Accessible")
}

// Restricted 验证Token
func Restricted(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	log.Debug(claims, "-----")
	return c.JSON(http.StatusOK, "OK")
}
